const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
var jsonParser = bodyParser.json();
let router = express.Router();
// a middleware sub-stack that handles GET requests to the /user/:id path
router.post(
    '/:id',
    jsonParser,
    function(req, res, next) {
        // if the user ID is 0, skip to the next router
        console.log(req.url);
        if (req.params.id === '0') next('route');
        // otherwise pass control to the next middleware function in this stack
        else if (req.params.id === '110') {
            new Promise((resolve, reject) => {
                fs.readFile(__dirname + '/../test.json', 'utf-8', (err, data) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(data);
                });
            })
                .then(data => {
                    console.log(data);
                    next();
                })
                .catch(err => {
                    next(err);
                });
        } else next();
    },
    function(req, res, next) {
        // render a regular page
        res.render('regular.art', {
            id: req.params.id
        });
    }
);

// handler for the /user/:id path, which renders a special page
router.post('/:id', jsonParser, function(req, res, next) {
    res.render('special.art', {
        id: req.params.id
    });
});

module.exports = {
    router: router
};
